﻿using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebAPI中介者模式示例MediatR_EFCroe_Thransaction.Command;
using WebAPI中介者模式示例MediatR_EFCroe_Thransaction.DAL;
using WebAPI中介者模式示例MediatR_EFCroe_Thransaction.Models;

namespace WebAPI中介者模式示例MediatR_EFCroe_Thransaction.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrdersController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly AppDbContext _dbContext;

        public OrdersController(IMediator mediator, AppDbContext dbContext)
        {
            _mediator = mediator;
            _dbContext = dbContext;
        }

        // 创建订单API
        [HttpPost]
        public async Task<IActionResult> CreateOrder([FromBody] CreateOrderCommand command)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var result = await _mediator.Send(command);
            return result.Success ? Ok(result) : BadRequest(result);
        }

        // 初始化测试数据（方便演示）
        [HttpGet("seed")]
        public async Task<IActionResult> SeedTestData()
        {
            // 清空现有数据
            _dbContext.Orders.RemoveRange(_dbContext.Orders);
            _dbContext.Products.RemoveRange(_dbContext.Products);
            _dbContext.Shipments.RemoveRange(_dbContext.Shipments);

            // 添加测试产品
            _dbContext.Products.Add(new Product { Name = "笔记本电脑", StockQuantity = 50 });
            _dbContext.Products.Add(new Product { Name = "智能手机", StockQuantity = 100 });

            await _dbContext.SaveChangesAsync();
            return Ok("测试数据已初始化，产品ID: 1(笔记本), 2(手机)");
        }
    }
}
